package com.juzipi.demo.config;

import com.juzipi.demo.handler.*;
import com.juzipi.demo.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private MyUserDetailService myUserDetailService;
    @Autowired
    private DataSource dataSource;



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //放行login，不用认证
                .antMatchers("/login").permitAll()
                .antMatchers("/logout").permitAll()
                //拦截所有请求
                .anyRequest().authenticated()
                .and().formLogin()//不加这个security的默认登录页面出不来
                .successHandler(getMyAuthenticationSuccessHandler())
                .failureHandler(getMyAuthenticationFailureHandler())
                //自定义异常出路
                .and().exceptionHandling()
                .authenticationEntryPoint(getMyAuthenticationEntryPoint())//未登录
                .accessDeniedHandler(getMyAccessDeniedHandler())//权限不足
                .and()
                //退出
                .logout().permitAll()
                .addLogoutHandler(getMyLogoutHandler())//退出操作
                .logoutSuccessHandler(getMyLogoutSuccessHandler())//退出成功
                .and();
        //关闭csrf防护
        http.csrf().disable();
//        http.formLogin()
//                //自定义入参
//                .usernameParameter("")
//                .passwordParameter("")
//                .
//        http.authorizeRequests()
//                .antMatchers("/**").permitAll()//放行所有
//                .antMatchers("/**/*.png").permitAll()//放行后缀为png的
//                .antMatchers("/user").hasIpAddress("127.0.0.1")//根据ip地址
//                .and()
        //记住我
        http.rememberMe()
                .tokenRepository(getPersistentTokenRepository())//设置数据源
//                .rememberMeParameter()//记住我的入参
                .tokenValiditySeconds(10)//超时时间,秒
                //自定义的登录逻辑
                .userDetailsService(myUserDetailService)
                .and();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置自定义的授权
        auth.userDetailsService(myUserDetailService).passwordEncoder(getPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }


    @Bean
    public PersistentTokenRepository getPersistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        //设置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        //自动建表,第二次一定要禁掉
        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }


    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }


    //登陆失败
    @Bean
    public MyAuthenticationFailureHandler getMyAuthenticationFailureHandler(){
        return new MyAuthenticationFailureHandler();
    }

    //登陆成功
    @Bean
    public MyAuthenticationSuccessHandler getMyAuthenticationSuccessHandler(){
        return new MyAuthenticationSuccessHandler();
    }

    //权限不足
    @Bean
    public MyAccessDeniedHandler getMyAccessDeniedHandler(){
        return new MyAccessDeniedHandler();
    }

    //未登录
    @Bean
    public MyAuthenticationEntryPoint getMyAuthenticationEntryPoint(){
        return new MyAuthenticationEntryPoint();
    }

    //退出的操作
    @Bean
    public MyLogoutHandler getMyLogoutHandler(){
        return new MyLogoutHandler();
    }

    //退出成功的
    @Bean
    public MyLogoutSuccessHandler getMyLogoutSuccessHandler(){
        return new MyLogoutSuccessHandler();
    }

}
